<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { UserApi } from '@/api/UserApi.ts'

const props = defineProps<{
  open: boolean
  userId: string | null
  userName?: string | null
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}>()

const confirmLoading = ref(false)

watch(
  () => props.open,
  (open) => {
    if (!open) {
      confirmLoading.value = false
    }
  }
)

const handleCancel = () => {
  emit('update:open', false)
}

const handleOk = async () => {
  if (!props.userId) {
    message.error('未获取到用户信息，无法删除')
    return
  }
  try {
    confirmLoading.value = true
    const success = await UserApi.deleteUser(props.userId)
    if (success) {
      message.success('删除成功')
      emit('update:open', false)
      emit('success')
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除失败')
  } finally {
    confirmLoading.value = false
  }
}
</script>

<template>
  <a-modal
    :open="open"
    title="删除用户"
    ok-text="删除"
    cancel-text="取消"
    :ok-button-props="{ danger: true }"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <p>
      确定要删除用户
      <strong>{{ userName || '此用户' }}</strong>
      吗？
    </p>
    <p class="tips">该操作不可恢复，请谨慎操作。</p>
  </a-modal>
</template>

<style scoped>
.tips {
  margin-top: 8px;
  color: #999;
}
</style>
